package com.fingard.dsp.bank.directbank.crbc01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.dsp.bank.directbank.crbc01.util.CrbankFileZip;
import com.fingard.text.StringHelper;
import com.fingard.util.FtpUtil;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.SmbFileUtil;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CRBC01ScheduleTask extends CRBC01Base implements IScheduleTask {

    private String receiptMainDir = "";

    @Override
    public void execTask(TaskTimerSet timerSet) {
        if (timerSet.taskNameList.toLowerCase().contains("pushreceipt")) {
            qryReceipt();
        }
    }

    private void qryReceipt() {
        try {
            receiptMainDir = FGBiz.dspCenter.dspSet.receiptMainDir;
            if (!StringHelper.isNullOrEmpty(receiptMainDir)) {
                if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                    if (!StringHelper.isNullOrEmpty(FGBiz.dspCenter.dspSet.receiptPushServerUrl)) {
                        receiptMainDir += File.separator + bankFront.bankCode + "Receipt";
                        pushReceiptToATS();
                    } else {
                        WriteBankLogLn("DSPSystem未配置回单文件推送地址");
                    }
                } else {
                    WriteBankLogLn("DSPSystem未配置回单文件共享目录");
                }
            } else {
                WriteBankLogLn("DSPSystem未配置回单文件下载保存主目录");
            }
        } catch (Exception e) {
            WriteBankLogLn(e);
        }
    }

    private void pushReceiptToATS() {
        try {
            File mainDir = new File(receiptMainDir);
            String todayDate = Format.Date8Format.format(new Date());
            List<StringBuilder> jsonList = new ArrayList<StringBuilder>();
            StringBuilder json = null;
            if (!mainDir.exists()) {
                mainDir.mkdirs();
            }
            File[] receiptFiles = mainDir.listFiles();
            //处理zip
            for (File file : receiptFiles) {
                String filePath = file.getPath();
                if (filePath.contains(".zip")) {
                    File upZipDir = new File(filePath.replace(".zip", ""));
                    if (!upZipDir.exists()) {
                        upZipDir.mkdir();
                        try {
                            CrbankFileZip.upZipFile(file.getPath(), upZipDir.getPath());
                        } catch (Exception e) {
                            e.printStackTrace();
                            WriteBankLogLn("解压" + file + "出错！" + e.getMessage());
                        }
                    }
                }
            }
            //处理pdf
            receiptFiles = mainDir.listFiles();
            int fileCount = 0;
            for (File file : receiptFiles) {
                if (file.isDirectory()) {
                    String actNum = null;
                    String tranDate = null;
                    boolean isToday = false;
                    String[] parms = file.getName().split("_");
                    if (parms.length > 1) {
                        actNum = parms[0];
                        tranDate = Format.Date10Format.format(Format.Date8Format.parse(parms[1]));
                        isToday = tranDate.equals(todayDate);
                    }
                    File[] subs = file.listFiles();
                    for (File receiptFile : subs) {
                        if (receiptFile.isFile() && receiptFile.getName().contains(".pdf")) {
                            String fileName = receiptFile.getName();
                            String localPath = receiptFile.getAbsolutePath();
                            String tmpByDate = Format.Date8Format.format(new Date());
                            String[] arg = PdfGenerateUtil.readFileOfPDF(receiptFile.getAbsolutePath()).split("\r\n");
                            if (StringHelper.isNullOrEmpty(actNum)) {
                                actNum = arg[33];
                            }
                            if (StringHelper.isNullOrEmpty(tranDate)) {
                                tranDate = arg[30].split(" ")[0];
                            }
                            String actCur = getBankConfig().getMapValueByKey("elereceiptAccountInfo", actNum);
                            if (StringHelper.isNullOrEmpty(actCur)) {
                                actCur = "1";
                            }
                            tmpByDate = tmpByDate.substring(0, 6) + "/" + tmpByDate.substring(6, 8) + "/" + reqHeader.bankCode + "/" + actNum + "/";
                            int result = -1;
                            String fileFlag = "";
                            String filePath = "";
                            String ftpFilePath = "";
                            if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir) && !"sftp".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                WriteBankLogLn("正在上传文件" + receiptFile + "至共享目录:" + FGBiz.dspCenter.dspSet.receiptShareDir);
                                result = SmbFileUtil.smbUploading(localPath, tmpByDate, FGBiz.dspCenter.dspSet.receiptShareDir);
                                fileFlag = "共享目录";
                            } else {
                                //ftp/sftp服务器
                                FtpSet ftpSet = FGBiz.dspCenter.dspConfig.getReceiptFtpSet("atsReceipt");
                                WriteBankLogLn("正在上传文件" + receiptFile + "至ftp/sftp目录:" + ftpSet.upDir);
                                //上传ftp/sftp服务器的地址
                                if ("false".equals(getBankConfig().getValueAsString("isCreateNewFile"))) {//是否可以新建目录
                                    filePath = fileName;//否
                                } else {
                                    filePath = tmpByDate + fileName;//是
                                }
                                ftpFilePath = StringHelper.trimEndFileSp(ftpSet.upDir) + "/" + filePath;
                                if ("sftp".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                    //上传至sftp
                                    result = FtpUtil.sftpUploading(ftpSet, localPath, ftpFilePath);
                                    fileFlag = "sftp服务器";
                                } else {
                                    //上传至ftp
                                    result = FtpUtil.ftpUploading(ftpSet, localPath, ftpFilePath);
                                    fileFlag = "ftp服务器";
                                }
                            }
                            if (result == 0 || result == 1) {
                                fileCount++;
                                if (result == 0) {
                                    WriteBankLogLn("文件上传成功");
                                } else {
                                    WriteBankLogLn("文件已存在共享目录无需重复上传");
                                }
                                //推送数据给ATS处理
                                json = new StringBuilder();
                                json.append("{");
                                json.append("\"actNum\":\"" + actNum + "\",");
                                json.append("\"actCur\":\"" + actCur + "\",");
                                json.append("\"receiptCode\":\"" + arg[32] + "\",");
                                json.append("\"receiptType\":\"" + "" + "\",");
                                json.append("\"receiptState\":\"" + "" + "\",");
                                json.append("\"oppActName\":\"" + "" + "\",");
                                json.append("\"oppActNum\":\"" + arg[36] + "\",");
                                json.append("\"moneyway\":\"" + "" + "\",");
                                json.append("\"amount\":\"" + arg[34].replace(",", "") + "\",");
                                json.append("\"tranSeqNo\":\"" + arg[32] + "\",");
                                json.append("\"tranCode\":\"" + "" + "\",");
                                json.append("\"tranDate\":\"" + tranDate + "\",");
                                if (!"false".equals(FGBiz.dspCenter.dspSet.receiptShareDir) && !"sftp".equals(FGBiz.dspCenter.dspSet.receiptShareDir)) {
                                    json.append("\"filePath\":\"" + tmpByDate + fileName + "\",");
                                } else {
                                    json.append("\"filePath\":\"" + filePath + "\",");//文件路径
                                }
                                json.append("\"fileType\":\"1\"");
                                json.append("},");
                                jsonList.add(json);
                            } else {
                                WriteBankLogLn("上传文件至" + fileFlag + "失败，请检查共享目录配置是否正确");
                            }

                        }
                    }
                    if (isToday) {//今日的电子回单可能会有新增，删除，以免影响今后下载
                        File zipFile = new File(file.getPath() + ".zip");
                        if (deleteAll(file)) {
                            WriteBankLogLn("成功删除" + file);
                        } else {
                            WriteBankLogLn("删除" + file + "失败");
                        }
                        if (deleteAll(zipFile)) {
                            WriteBankLogLn("成功删除" + zipFile);
                        } else {
                            WriteBankLogLn("删除" + zipFile + "失败");
                        }
                    }
                }

            }
            if (fileCount > 0 && jsonList.size() > 0) {
                String sendStr = "transType=downloadreceipt&data={\"rows\":[";
                StringBuilder sendJson = new StringBuilder();
                String strValue = bankFront.getStrValueByFor("receiptDataCount", "");
                if (StringHelper.isNullOrEmpty(strValue)) {
                    strValue = "500";
                }
                Integer receiptDataCount = Integer.valueOf(strValue);
                for (int i = 0; i < jsonList.size(); i++) {
                    if (i > 0 && ((i + 1) % receiptDataCount == 0 || i == jsonList.size() - 1)) {
                        jsonList.get(i).deleteCharAt(jsonList.get(i).length() - 1);
                        sendJson.append(jsonList.get(i));
                        sendJson.append("]}");
                        String[] data = sendToATS(sendStr + sendJson.toString());
                        if (data[0].length() == 0 && "ok".equals(data[1])) {
                            WriteBankLogLn("5.推送数据到ATS成功" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                        } else {
                            WriteBankLogLn("5.推送数据到ATS失败" + ((i + 1) % receiptDataCount > 0 ? (i + 1) % receiptDataCount : receiptDataCount) + "笔,请查看数据");
                        }
                        sendJson = new StringBuilder();
                    } else {
                        sendJson.append(jsonList.get(i));
                    }
                }
                WriteBankLogLn("成功保存了" + fileCount + "个文件");
            } else {
                WriteBankLogLn("成功保存文件条数为0，不需要推送数据到ATS");
            }

        } catch (Exception e) {
            e.printStackTrace();
            WriteBankLogLn(e.getMessage());
        }
    }

    private boolean deleteAll(File file) {
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        }
        if (file.isDirectory()) {
            File[] subs = file.listFiles();
            for (File sub : subs) {
                if (!deleteAll(sub)) {
                    return false;
                }
            }
            return file.delete();
        }
        return false;
    }
}
